import logging
import unittest
import requests
import app
from api.p2pApi import LoginApi
from api.tender_api import TenderApi
from common.DButils import DButils
from common.read_json_util import assert_api

# 获取投资详情
from common.three_util import third_request


class TestTender(unittest.TestCase):
    # 初始化,实例化请求session和调用接口
    def setUp(self) -> None:
        self.session = requests.session()
        self.tender_api = TenderApi()
        self.login_api = LoginApi()
    def tearDown(self) -> None:
        # 关闭session
        self.session.close()
    def test01_get_tender(self):
        response = self.tender_api.get_loaninfo(self.session,app.loan_id)
        logging.info("response={}".format(response.json()))
        assert_api(self,response,200,200,"OK")
        self.assertEqual(app.loan_id,response.json().get('data').get('loan_info').get("id"))
# 投资方法
    def test02_trust_tender(self):
        # 登录
        response = self.login_api.login_api(self.session,app.phone2,app.pwd)
        logging.info("respnse={}".format(response.json()))
        # 投资
        response = self.tender_api.tender_trust(self.session,app.loan_id,amount="100")
        self.assertEqual(200,response.json().get("status"))
        # 第三方投资
        form_data= response.json.get("description").get("form")
        response = third_request(form_data)
        logging.info("response={}".format(response.json()))
        self.assertEqual(200,response.json().get("status"))
        self.assertEqual("InitiativeTender OK",response.text)
        # 获取我的投资列表
    def test03_get_my_tender(self):
        # 登录
        response = self.login_api.login_api(self.session, app.phone2, app.pwd)
        logging.info("respnse={}".format(response.json()))
        # 获取我的投资列表
        status = "tender"
        response = self.tender_api.get_my_tender_list(self.session,status)
        logging.info("response = {}".format(response.json()))
        self.assertEqual(200,response.status_code)
        # 获取预期投资条款_连接数据库
        tender_sql = "select count(*) from czbk_finance.fn_tender f inner join czbk_member.mb_meber m on f.member_id = m.id where m.id "
        result = DButils.select_sql(tender_sql.format(app.phone2))
        print(result[0][0])
        # 获取实际投资条数
        total_items = response.json().get("total_items")
        self.assertEqual(result[0][0],total_items)

        # 用户不存在,登录失败
    def test04_login_fail_phone_is_not_exist(self):
        no_phone = "13846783769"
        del_sql = "delete from czbk_member.mb_member where phone = {}"
        DButils.update_sql(del_sql.format((no_phone)))
        response = self.login_api.login_api(self.session,no_phone)
        logging.info("login response = {}".format(response.json()))
        assert_api(self,response,200,100,"用户不存在")






